package com.sudolink.isp.ui.eula;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * EULAViewer.java
 *
 * Created on Apr 25, 2010, 8:22:11 AM
 * @version 4-25-2010
 */






import com.sudolink.isp.app.Application;
import java.io.*;
import javax.swing.JOptionPane;
/**
 *
 * @author matsu
 */
public class EULAViewer extends javax.swing.JFrame {
    //TODO: add better exception support... Maybe improve logger?

    /** Creates new form EULAViewer */
    public EULAViewer( String licensePath, EULALaunchable application ) {
        this.setUndecorated(true);
        initComponents();
        String licenseText = this.readTextFromJar(licensePath);
        licenseTextArea.setText(licenseText);
        licenseTextArea.setCaretPosition(0);
        app = application;
        setLocationRelativeTo(null);

    }

    public void promptEULA() {
        if ( isEulaAccepted() ) {
            launchApplication(args);
        } else {
            setVisible(true);
        }
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        backgroundPanel = new javax.swing.JPanel();
        foregroundPanel = new javax.swing.JPanel();
        labelTopHeader = new javax.swing.JLabel();
        jScrollPane = new javax.swing.JScrollPane();
        licenseTextArea = new javax.swing.JTextArea();
        checkboxEulaAgree = new javax.swing.JCheckBox();
        jButton_Decline = new javax.swing.JButton();
        jButton_Accept = new javax.swing.JButton();

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 100, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 100, Short.MAX_VALUE)
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setAlwaysOnTop(true);
        setBackground(new java.awt.Color(102, 102, 102));

        backgroundPanel.setBackground(new java.awt.Color(129, 156, 161));

        labelTopHeader.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        labelTopHeader.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        labelTopHeader.setText("License Agreement");

        jScrollPane.setHorizontalScrollBar(null);

        licenseTextArea.setColumns(20);
        licenseTextArea.setEditable(false);
        licenseTextArea.setLineWrap(true);
        licenseTextArea.setRows(5);
        licenseTextArea.setWrapStyleWord(true);
        jScrollPane.setViewportView(licenseTextArea);

        checkboxEulaAgree.setText("I agree to be bound by the terms of this license.");

        jButton_Decline.setText("Decline");
        jButton_Decline.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_DeclineActionPerformed(evt);
            }
        });

        jButton_Accept.setText("Accept");
        jButton_Accept.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_AcceptActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout foregroundPanelLayout = new org.jdesktop.layout.GroupLayout(foregroundPanel);
        foregroundPanel.setLayout(foregroundPanelLayout);
        foregroundPanelLayout.setHorizontalGroup(
            foregroundPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(foregroundPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(foregroundPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, foregroundPanelLayout.createSequentialGroup()
                        .add(201, 201, 201)
                        .add(jButton_Decline)
                        .add(18, 18, 18)
                        .add(jButton_Accept)
                        .add(19, 19, 19))
                    .add(foregroundPanelLayout.createSequentialGroup()
                        .add(labelTopHeader, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 480, Short.MAX_VALUE)
                        .addContainerGap())
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, foregroundPanelLayout.createSequentialGroup()
                        .add(foregroundPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                            .add(jScrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 480, Short.MAX_VALUE)
                            .add(foregroundPanelLayout.createSequentialGroup()
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 223, Short.MAX_VALUE)
                                .add(checkboxEulaAgree)))
                        .addContainerGap())))
        );
        foregroundPanelLayout.setVerticalGroup(
            foregroundPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(foregroundPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(labelTopHeader)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jScrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 258, Short.MAX_VALUE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(checkboxEulaAgree)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(foregroundPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jButton_Decline)
                    .add(jButton_Accept))
                .addContainerGap())
        );

        org.jdesktop.layout.GroupLayout backgroundPanelLayout = new org.jdesktop.layout.GroupLayout(backgroundPanel);
        backgroundPanel.setLayout(backgroundPanelLayout);
        backgroundPanelLayout.setHorizontalGroup(
            backgroundPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(backgroundPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(foregroundPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        backgroundPanelLayout.setVerticalGroup(
            backgroundPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(backgroundPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(foregroundPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, backgroundPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(backgroundPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton_DeclineActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_DeclineActionPerformed
        this.dispose();
    }//GEN-LAST:event_jButton_DeclineActionPerformed

    private void jButton_AcceptActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_AcceptActionPerformed
        if ( this.checkboxEulaAgree.isSelected() )
        {
            Application.setEULASigned(true);
            app.launchApplication( args );
            this.dispose();
        }
        else
        {
            javax.swing.JOptionPane.showMessageDialog(this,
                    "You must select the checkbox if you accept the license agreement.");
        }
    }//GEN-LAST:event_jButton_AcceptActionPerformed

    private boolean isEulaAccepted()
    {
        return Application.isEULASigned();
    }

    public void launchApplication(String[] args)
    {
        app.launchApplication(args);
    }

//    private void serialize()
//    {
//        String eulaAgreePath = getLicenseAgreePath();
//        File f = new File( eulaAgreePath );
//        if ( ! f.exists() )
//        {
//            f.getParentFile().mkdirs();
//        }
//
//        try
//        {
//            FileOutputStream fs = new FileOutputStream( eulaAgreePath );
//            ObjectOutputStream os = new ObjectOutputStream( fs );
//            os.writeObject( getLicenseAgree() );
//            os.close();
//        }
//        catch ( IOException ioe )
//        {
//            Logger.log("Failed to save license agreement information.");
//            JOptionPane.showMessageDialog(this,
//                    "Error: Unable to save license agreement information.");
//            Logger.log(Logger.Level.WARNING , ioe );
//        }
//        
//    }
    
//    @SuppressWarnings("unchecked")
//    private void deserialize()
//    {
//        java.util.HashMap<String,String> license = new HashMap<String, String>();
//        String eulaAgreePath = getLicenseAgreePath();
//        if ( new File(eulaAgreePath ).exists() )
//        {
//            try
//            {
//                FileInputStream fis = new FileInputStream(eulaAgreePath);
//                ObjectInputStream ois = new ObjectInputStream( fis );
//
//                license = ( java.util.HashMap<String,String> ) ois.readObject();
//                ois.close();
//                Logger.log("Success deserializing EULA object");
//            }
//            catch( Exception e ) { 
//                
//                Logger.severe("Error deserializing EULA object.");
//                JOptionPane.showMessageDialog(this,
//                    "Error: Unable to open EULA.");
//                Logger.log(Logger.Level.SEVERE, e);
//                System.exit(1);
//            }
//            
//        }
//        licenseAgree = license;
//    }

//    /**
//     * @return the licenseAgreePath
//     */
//    public String getLicenseAgreePath() {
//        return licenseAgreePath;
//    }
//
//    /**
//     * Sets the path to the
//     * license accept file.  This is the file that will be
//     * checked to see if the license has been agreed to or not.
//     * @param licenseAgreePath the licenseAgreePath to set
//     */
//    public final void setLicenseAgreePath(String licenseAgreePath) {
//        this.licenseAgreePath = licenseAgreePath;
//    }

    /**
     * Reads the data from a text file that is stored in the jar file as a
     * resource.
     * @param path The path to the resource in the same jar file as this class.
     * @return
     */
    public final String readTextFromJar(String path) {
        String thisLine;
        String fileText = "";

        try {
          InputStream is = getClass().getResourceAsStream(path);
          BufferedReader br = new BufferedReader
             (new InputStreamReader(is));
          while ((thisLine = br.readLine()) != null) {
             fileText += thisLine + "\n";
             }
          }
        catch (Exception e) {
            
            Logger.severe("Error reading EULA text file as resource from jar.");
            Logger.log( Logger.Level.SEVERE, e );
            JOptionPane.showMessageDialog(this,
                    "Error: Unable to open EULA.");
            //Abort application
            System.exit(1);
            
          }
        return fileText;
  }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel backgroundPanel;
    private javax.swing.JCheckBox checkboxEulaAgree;
    private javax.swing.JPanel foregroundPanel;
    private javax.swing.JButton jButton_Accept;
    private javax.swing.JButton jButton_Decline;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane;
    private javax.swing.JLabel labelTopHeader;
    private javax.swing.JTextArea licenseTextArea;
    // End of variables declaration//GEN-END:variables
    //The application which will be launched if the user accepts the EULA.
    private EULALaunchable app;
    //Arguments to be passed to the application from the command line.
    private String[] args;

}
